/*
 * @Description: 权限
 * @Author: ZY
 * @Date: 2020-12-28 09:12:46
 * @LastEditors: ZY
 * @LastEditTime: 2021-01-27 19:36:01
 */

import NProgress from "nprogress";
import "nprogress/nprogress.css";
// import { useI18n } from 'vue-i18n'
import router from "@/router";
import { RouteLocationNormalized } from "vue-router";
import { useStore } from "./store";
import { UserActionTypes } from "./store/modules/user/action-types";
// import { PermissionActionType } from './store/modules/permission/action-types'
import { ElMessage } from "element-plus";
import Cookies from "js-cookie";
import { asyncRouterMap, constantRouterMap } from "@/router";
// import whiteList from './config/default/whitelist'

const whiteList = ["/login", "/front/index", "/front/test"];
// import settings from '@/config/default/setting.config'
NProgress.configure({ showSpinner: false });
// import i18n from '@/lang/index'
// const { t} =i18n.global
// const getPageTitle = (key: string) => {
//   const i18n = useI18n()
//   const title = settings.title
//   const hasKey = i18n.te(`route.${key}`)
//   if (hasKey) {
//     const pageName = i18n.t(`route.${key}`)
//     return `${pageName} - ${title}`
//   }
//   return `${title}`
// }

router.beforeEach(
  async (
    to: RouteLocationNormalized,
    _: RouteLocationNormalized,
    next: any
  ) => {
    console.log('跳转')

    // /* 路由跳转删除message */
    // $('.el-message').each((index, item) => {
    //     $(item).css('display', 'none');

    //   // $(item).remove();//remove方案有时会导致this.$el.parentNode is null  message报错
    // })
    // if (process.client) {
      // try {
      // } catch (error) { }
    // }

    // if (to.matched?.length) {
    //   if (to.query.Name) {
    //     to.matched[to.matched?.length - 1].meta.title =to.query.Name
    //   }else{
    //     to.matched[to.matched?.length - 1].meta.title =t('collection.AddDataSet.add')
    //   }

    // }


    // Start progress bar
    NProgress.start();
    const store = useStore();
    store.dispatch(UserActionTypes.ACTION_GET_JUMP_LOADING, true);
    // Determine whether the user has logged in


    if (useStore().state.user.token) {

      if (to.path === "/") {
        next("/home");
        NProgress.done();
      }
      if (to.path === "/login") {
        // If is logged in, redirect to the home page
        next();
        // next(`/login`)
        NProgress.done();
      } else {

        if (store.state.user.routerList?.length === 0) {
          try {

            // Note: roles must be a object array! such as: ['admin'] or ['developer', 'editor']
            await store.dispatch(
                UserActionTypes.ACTION_GET_USER_INFO,
                undefined
            );
            await store.dispatch(
                UserActionTypes.ACTION_GET_ROUTER_LIST,
                undefined
            );
            let userRouterMap: any = new Map();
            const routerMapFun = (list: any) => {
              list?.forEach((item: any) => {

                  userRouterMap.set(item.code, item);
                routerMapFun(item.children);
              })
            }

            routerMapFun(store.state.user.routerList);
            const accessedRouters = filterAsyncRoutes(asyncRouterMap, userRouterMap);
            // 动态添加可访问路由表


            const roles = store.state.user.roles;

            next({...to, replace: true});
          } catch (err) {
            // Remove token and redirect to login page
            store.dispatch(UserActionTypes.ACTION_RESET_TOKEN, undefined);
            ElMessage.error(err || "Has Error");
            next(`/login?redirect=${to.path}`);
            NProgress.done();
          }
        } else {

          if (to.matched.length === 0) {
            if (_.name) {
              next({name: _.name as any})
            } else {
              next('/404')
            }
          } else {
            next();
          }
        }
      }
    } else {
      // Has no token
      if (whiteList.indexOf(to.path) !== -1) {
        // In the free login whitelist, go directly
        next();
      } else {
        // next()
        // ElMessage.error("认证过期请重新登录");
        next(`/login`);
        // Other pages that do not have permission to access are redirected to the login page.
        // next(`/login?redirect=${to.path}`)
        NProgress.done();
      }
    }
  }
);

router.afterEach((to: RouteLocationNormalized) => {


  /* 路由跳转删除message */
  // $('.el-message').each((index, item) => {
  //     $(item).css('display', 'none');

  //   // $(item).remove();//remove方案有时会导致this.$el.parentNode is null  message报错
  // })

  const store = useStore();
  store.dispatch(UserActionTypes.ACTION_GET_JUMP_LOADING, false);
  // setTimeout(()=>{
  //   Cookies.set('jumpLoading', 'false')
  // },100)
  // Cookies.set('jumpLoading', 'false')
  //
  // Finish progress bar
  // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
  NProgress.done();

  // set page title
  // document.title = getPageTitle(to.meta.title)
});


/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes: any, roleRights: Map) {

  const res: any = []
  routes.forEach((route: any) => {
    const tmp = {...route}
    let type = hasPermission(roleRights, tmp);

    let init = roleRights.get(tmp.name) || {};
    if (type == 2 || type == 3) {
      //第一级 ｜｜ 看板驾驶舱两个特例
      if (init.parentId === '0') {
        router.addRoute(tmp);
      }
      res.push(tmp)
    } else if (type == 1) {

      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roleRights)
      }
      router.addRoute(tmp);

      res.push(tmp)
    }
  })


  return res
}


/**
 *
 * @param roleRights 接口返回的当前用户的所有权限菜单
 * @param routes
 * @returns {boolean|*}
 */
function hasPermission(roleRights:any, route:any) {


  // return roleRights.map((item,index)=>{

  //     if ( item.code === route.name&&item.category==1) {
  //   return 1
  // } else if(item.code === route.name&&item.category==2) {
  //   return 2
  // }else{
  //   return 3
  // }
  // })




  // if (roleRights.filter(item=>item.code == route.name&&item.category==1)) {
  //   return [1,roleRights.filter(item=>item.code === route.name&&item.category==1)[0]]
  // } else if(roleRights.filter(item=>item.code == route.name&&item.category==2)) {

  //   return [2]
  // }else{
  //   return [3]
  // }
  return roleRights.get(route.name)?.category||3;
  // if (
  //   // (route.meta && route.meta.permission) ||
  //    roleRights.some((item:any) => item.code === route.name&&item.category==1)) {
  //   return 1
  // } else if( roleRights.some((item:any) => item.code === route.name&&item.category==2)) {
  //   return 2
  // }else{
  //   return 3
  // }
}
